package com.hko.qrip.service.impl;

import it.sauronsoftware.ftp4j.FTPFile;

import java.io.File;
import java.io.FilenameFilter;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;

import org.springframework.beans.factory.annotation.Autowired;

import com.hko.qrip.bean.WtwsAlert;
import com.hko.qrip.dao.FtpLogDao;
import com.hko.qrip.dao.WtwsDao;
import com.hko.qrip.manager.FTPManager;
import com.hko.qrip.service.WtwsService;
import com.hko.qrip.util.QripJobOptions;

public class WtwsServiceImpl implements WtwsService {

	private static String TIMEROW = "ISSUE TIME:";
	private static String TURB = "TURB";
	private static String TURB_WITH_WS = "T";
	private static String MOD_TURB = "MOD";
	private static String SEV_TURB = "SEV";
	private static String APPROACH = "APP";
	private static String DEPARTURE = "DEP";
	private static String APPROACH_S = "A";
	private static String DEPARTURE_S = "D";

	@Autowired
	private QripJobOptions jobOptions;

	@Autowired
	private WtwsDao wtwsDao;

	@Autowired
	private FtpLogDao ftpLogDao;

	@Override
	public int insertAlert(WtwsAlert alert) throws SQLException {
		return wtwsDao.insertAlert(alert);
	}

	@Override
	public int insertTurbAlert(WtwsAlert alert) throws SQLException {
		return wtwsDao.insertTurbAlert(alert);
	}

	@Override
	public void doSync() throws Exception {
		System.out.println("[INFO] Wtws sync service started");
		File[] lrFiles = downloadAlertFile();

		for (File file : lrFiles) {
			ArrayList<WtwsAlert> alerts = getAlertFile(file);
			int changeCount = 0;
			int turbChangeCount = 0;
			for (WtwsAlert alert : alerts) {
				if (TURB.equals(alert.getAlertType())) {
					turbChangeCount += insertTurbAlert(alert);
				} else {
					changeCount += insertAlert(alert);
				}

			}
			file.delete();
			System.out.println(changeCount + ", " + turbChangeCount + " alerts inserted: " + file.getName());
			ftpLogDao.insertTableLog(file.getName(), changeCount + turbChangeCount, alerts.size(), "");
		}
		System.out.println("[INFO] Wtws sync service ended");

	}

	private File[] downloadAlertFile() throws Exception {
		FTPManager fm = new FTPManager(jobOptions.getFtpHost(), jobOptions.getFtpUser(), jobOptions.getFtpPassword());
		fm.ftpLogin();
		fm.changeDir(jobOptions.getFtpPath());
		FTPFile[] files = fm.listFiles("wtws*.out");
		for (FTPFile file : files) {
			fm.downloadAndDeleteFile(jobOptions.getLocalFilePath() + file.getName(), file.getName());
			System.out.println("downloaded: " + file.getName());
			ftpLogDao.insertFtpLog(file.getName());
		}
		fm.close();

		File lrDir = new File(jobOptions.getLocalFilePath());
		File[] lrFiles = lrDir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File arg0, String arg1) {
				if (arg1.contains("wtws")) {
					return true;
				}
				return false;
			}
		});
		return lrFiles;
	}

	private ArrayList<WtwsAlert> getAlertFile(File file) throws Exception {
		ArrayList<WtwsAlert> resultList = new ArrayList<WtwsAlert>();

		Scanner fin = new Scanner(file);
		Timestamp lineTs = new Timestamp(0L);
		while (fin.hasNextLine()) {
			String line = fin.nextLine().trim();
			if (line.contains(TURB)) {
				WtwsAlert alert = new WtwsAlert();
				alert.setDatetime(lineTs);
				alert.setCorridor(line.split(" ")[0]);
				if (MOD_TURB.equals(line.split(" ")[1].trim())) {
					alert.setMagnitude(2);
				} else if (SEV_TURB.equals(line.split(" ")[1].trim())) {
					alert.setMagnitude(3);
				} else
					alert.setMagnitude(0);
				alert.setLocation(line.split(" ")[3]);
				alert.setAlertType(TURB);
				if (!resultList.contains(alert)) {
					resultList.add(alert);
				}
			} else if (line.contains(TIMEROW)) {
				Date date = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(line.substring(12));
				lineTs = new Timestamp(date.getTime());
			} else {
				WtwsAlert alert = new WtwsAlert();
				alert.setDatetime(lineTs);
				alert.setCorridor(line.split(" ")[0]);
				alert.setMagnitude(Integer.parseInt(line.split(" ")[2].replace("K", "").replace("+", "")));
				alert.setLocation(line.split(" ")[3]);
				alert.setAlertType(line.split(" ")[1]);
				if (!resultList.contains(alert)) {
					resultList.add(alert);
				}

				if (line.contains(TURB_WITH_WS)) {
					WtwsAlert turbAlert = new WtwsAlert();
					turbAlert.setDatetime(lineTs);
					turbAlert.setCorridor(alert.getCorridor());
					if (line.contains(MOD_TURB)) {
						turbAlert.setMagnitude(2);
					} else if (line.contains(SEV_TURB)) {
						turbAlert.setMagnitude(3);
					} else
						turbAlert.setMagnitude(0);
					if (alert.getCorridor().contains(APPROACH_S)) {
						turbAlert.setLocation(APPROACH);
					} else if (alert.getCorridor().contains(DEPARTURE_S)) {
						turbAlert.setLocation(DEPARTURE);
					} else {
						turbAlert.setLocation(" ");
					}
					turbAlert.setAlertType(TURB);
					if (!resultList.contains(turbAlert)) {
						resultList.add(turbAlert);
					}
				}
			}
		}
		fin.close();

		return resultList;
	}

}
